<script lang="ts" setup>
import { ref } from 'vue'
import { regConst } from './regConst'
import { getRegistrationByPage } from '@/services/registration'
import { mockPay, repay } from '@/services/payment'
import { onReachBottom, onShow } from '@dcloudio/uni-app'
import type { BaseRegistration } from '@/types/registration'
import dayjs from 'dayjs'
import isBetween from 'dayjs/plugin/isBetween'
import { generateRandomDigitString } from '@/utils/randomString'

dayjs.extend(isBetween)
const regConstData = regConst()
const list = ref<BaseRegistration[]>([])
const json = ref(regConstData.json)
const page = ref(1)
const length = ref(50)
const reload = ref(true)

const moreHandle = (id: number) => {
  uni.navigateTo({
    url: '/registration/registration_info/registration_info?id=' + id,
  })
}

//处理重新支付事件
const payHandle = (id: number, index: number) => {
  uni.showModal({
    title: '提示消息',
    content: '您确定支付该笔挂号费？',
    success: async (res) => {
      if (res.confirm) {
        let data = {
          id,
        }
        await repay(data).then((res) => {
          let payrReqResult = res.result
          console.log(payrReqResult)
          uni.showModal({
            title: '提示信息',
            content: '确认挂号并支付？',
            confirmText: '模拟支付',
            cancelText: '取消',
            success: async (res) => {
              if (res.confirm) {
                let data = {
                  outTradeNo: payrReqResult.outTradeNo,
                  transactionId: generateRandomDigitString(dayjs().format('YYYYMMDD'), 12),
                }
                await mockPay(data).then((res) => {
                  if (res.result) {
                    uni.showToast({
                      icon: 'success',
                      title: '付款成功',
                    })
                  } else {
                    uni.showToast({
                      icon: 'none',
                      title: '付款异常，请联系客服',
                    })
                  }
                  list.value[index].paymentStatus = 2
                })
              } else if (res.cancel) {
                uni.showToast({
                  icon: 'none',
                  title: '取消支付',
                })
              }
            },
          })
        })
      }
    },
  })
}

const loadData = () => {
  let data = {
    page: page.value,
    length: length.value,
  }
  getRegistrationByPage(data).then((res) => {
    let resultList = res.result.list
    for (let one of resultList) {
      if (['主任医师', '副主任医师'].includes(one.job)) {
        one.job = '专家'
      } else {
        one.job = '普通'
      }

      let temp = dayjs(one.date)
      one.month = temp.format('MM')
      one.day = temp.format('DD')
      one.time = json.value[one.slot]
      let now = dayjs()
      let rangeStart = dayjs(`${one.date} ${one.time}`)
      let rangeEnd = rangeStart.add(30, 'minute')
      //判断该挂号记录是否已过期
      if (
        one.paymentStatus == 1 &&
        (now.isBetween(rangeStart, rangeEnd) || now.isAfter(rangeEnd))
      ) {
        one.discarded = true
      } else {
        one.discarded = false
      }
    }
    list.value = list.value.concat(resultList)
  })
}

onReachBottom(() => {
  page.value++
  loadData()
})

onShow(() => {
  if (reload.value) {
    page.value = 1
    list.value = []
    loadData()
  }
})
</script>

<template>
  <view>
    <view class="registration" v-for="(one, index) of list" :key="index">
      <view class="calendar">
        <view class="month">{{ one.month }}月</view>
        <view class="day">{{ one.day }}日</view>
      </view>
      <view class="content">
        <view class="row">
          <text class="deptSubName">{{ one.name }}（{{ one.job }}）</text>
          <view class="more" @tap="moreHandle(one.id)">
            <text>more</text>
            <u-icon name="arrow-right" color="#aaa" size="14"></u-icon>
          </view>
        </view>
        <view class="row">
          <text class="address">地址：{{ one.location }}</text>
        </view>
        <view class="row">
          <text class="datetime">时间：{{ one.date }} {{ one.time }}</text>
        </view>
        <view class="unpaid" v-if="one.paymentStatus == 1 && !one.discarded">
          <u-button type="primary" size="small" @click="payHandle(one.id, index)">待支付</u-button>
        </view>
        <view class="paid" v-if="one.paymentStatus == 2">已支付</view>
        <view class="refund" v-if="one.paymentStatus == 3">已退款</view>
        <view class="discarded" v-if="one.paymentStatus == 4">已过期</view>
      </view>
    </view>
  </view>
</template>

<style lang="less">
@import url(registration_list.less);
</style>
